import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class DiyService extends BaseService<any> {
  private readonly logger = new Logger(DiyService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * getPage
   * 对应 PHP: DiyService_admin::getPage()
   * 逻辑类型: undefined - undefined
   */
  async getPage(where: any[]) {
    // 基于PHP真实逻辑: getPage
    // PHP原文: $where[] = ['site_id', '=', $this->site_id];         $field = 'id,site_id,title,page_title,name,template,type,mode,is_default,share,visit_count,create...
where[] = ['site_id', '=', this.site_id];
        const field = 'id,site_id,title,page_title,name,template,type,mode,is_default,share,visit_count,create_time,update_time,value';
        const order = "update_time desc";
        const search_model = this.model.where([['site_id', '=', this.site_id))).withSearch(["title", "type", 'mode', 'addon_name'), where).field(field).order(order).append(['type_name', 'type_page', 'addon_name')];
        return this.pageQuery(search_model);
    }

    /**
     * 获取自定义页面分页列表，轮播搜索组件用
     * 查询微页面，数据排除存在轮播搜索组件的
     * @return * @throws DbBusinessException
     */
    async getPageByCarouselSearch()
    {
        const field = 'id,title,page_title,name,type,create_time,value';
        const order = "update_time desc";
        const search_model = this.model
            .whereOr([
                [
                    ['type', '=', 'DIY_PAGE'],
                    ['site_id', '=', this.site_id],
                    ['value', 'not like',
                        [
                            '%"position":"top_fixed"%',
                            '%"position":"right_fixed"%',
                            '%"position":"bottom_fixed"%',
                            '%"position":"left_fixed"%',
                            '%"position":"fixed"%'
                        ]
                    ]
                ],
                [
                    ['type', '<>', 'DIY_PAGE'],
                    ['site_id', '=', this.site_id],
                    ['is_default', '=', 0],
                    ['value', 'not like',
                        [
                            '%"position":"top_fixed"%',
                            '%"position":"right_fixed"%',
                            '%"position":"bottom_fixed"%',
                            '%"position":"left_fixed"%',
                            '%"position":"fixed"%'
                        ]
                    ]
                )
            )).field(field).order(order).append(['type_name', 'type_page', 'addon_name')];
        return this.pageQuery(search_model);
    }

    /**
     * 获取自定义页面列表
     * @param where
     * @param string field
     * @return * @throws DataNotFoundBusinessException
     * @throws DbBusinessException
     * @throws ModelNotFoundBusinessException
     */
    async getList(where = [), field = 'id,title,page_title,name,template,type,mode,is_default,share,visit_count,create_time,update_time')
    {
        const order = "update_time desc";
        return this.model.where([['site_id', '=', this.site_id))).withSearch(["title", "type", 'mode'), where).field(field).order(order).select().toArray(];
    }

    /**
     * 获取自定义页面信息
     * @param int id
     * @return */
    async getInfo(int id)
    {
        const field = 'id,site_id,title,page_title,name,template,type,mode,value,is_default,is_change,share,visit_count';
        return this.model.field(field).where([['id', '=', id], ['site_id', '=', this.site_id))).findOrEmpty().toArray(];
    }

    async getInfoByName(string name)
    {
        const field = 'id,site_id,title,page_title,name,template,type,mode,value,is_default,is_change,share,visit_count';
        return this.model.field(field).where([['name', '=', name], ['site_id', '=', this.site_id], ['is_default', '=', 1))).findOrEmpty().toArray(];
    }

    /**
     * 查询数量
     * @param where
     * @return int
     * @throws DbBusinessException
     */
    async getCount(where = [))
    {
        return this.model.where([['site_id', '=', this.site_id))).withSearch(.type, where).count(];
    }

    /**
     * 添加自定义页面
     * @param data
     * @return mixed
     */
    async add(data)
    {
        if (!data.site_id)) {
            data.site_id = this.site_id;
  }

  /**
   * getPageByCarouselSearch
   * 对应 PHP: DiyService_admin::getPageByCarouselSearch()
   * 逻辑类型: undefined - undefined
   */
  async getPageByCarouselSearch() {
    // 基于PHP真实逻辑: getPageByCarouselSearch
    // PHP原文: $field = 'id,title,page_title,name,type,create_time,value';         $order = "update_time desc";         $search_model = $this->model             ->wh...
const field = 'id,title,page_title,name,type,create_time,value';
        const order = "update_time desc";
        const search_model = this.model
            .whereOr([
                [
                    ['type', '=', 'DIY_PAGE'],
                    ['site_id', '=', this.site_id],
                    ['value', 'not like',
                        [
                            '%"position":"top_fixed"%',
                            '%"position":"right_fixed"%',
                            '%"position":"bottom_fixed"%',
                            '%"position":"left_fixed"%',
                            '%"position":"fixed"%'
                        ]
                    ]
                ],
                [
                    ['type', '<>', 'DIY_PAGE'],
                    ['site_id', '=', this.site_id],
                    ['is_default', '=', 0],
                    ['value', 'not like',
                        [
                            '%"position":"top_fixed"%',
                            '%"position":"right_fixed"%',
                            '%"position":"bottom_fixed"%',
                            '%"position":"left_fixed"%',
                            '%"position":"fixed"%'
                        ]
                    ]
                )
            )).field(field).order(order).append(['type_name', 'type_page', 'addon_name')];
        return this.pageQuery(search_model);
    }

    /**
     * 获取自定义页面列表
     * @param where
     * @param string field
     * @return * @throws DataNotFoundBusinessException
     * @throws DbBusinessException
     * @throws ModelNotFoundBusinessException
     */
    async getList(where = [), field = 'id,title,page_title,name,template,type,mode,is_default,share,visit_count,create_time,update_time')
    {
        const order = "update_time desc";
        return this.model.where([['site_id', '=', this.site_id))).withSearch(["title", "type", 'mode'), where).field(field).order(order).select().toArray(];
    }

    /**
     * 获取自定义页面信息
     * @param int id
     * @return */
    async getInfo(int id)
    {
        const field = 'id,site_id,title,page_title,name,template,type,mode,value,is_default,is_change,share,visit_count';
        return this.model.field(field).where([['id', '=', id], ['site_id', '=', this.site_id))).findOrEmpty().toArray(];
    }

    async getInfoByName(string name)
    {
        const field = 'id,site_id,title,page_title,name,template,type,mode,value,is_default,is_change,share,visit_count';
        return this.model.field(field).where([['name', '=', name], ['site_id', '=', this.site_id], ['is_default', '=', 1))).findOrEmpty().toArray(];
    }

    /**
     * 查询数量
     * @param where
     * @return int
     * @throws DbBusinessException
     */
    async getCount(where = [))
    {
        return this.model.where([['site_id', '=', this.site_id))).withSearch(.type, where).count(];
    }

    /**
     * 添加自定义页面
     * @param data
     * @return mixed
     */
    async add(data)
    {
        if (!data.site_id)) {
            data.site_id = this.site_id;
  }

  /**
   * getList
   * 对应 PHP: DiyService_admin::getList()
   * 逻辑类型: undefined - undefined
   */
  async getList(where: any[], field: any[]) {
    // 基于PHP真实逻辑: getList
    // PHP原文: $order = "update_time desc";         return $this->model->where([['site_id', '=', $this->site_id]])->withSearch(["title", "type", 'mode'], $where)->fi...
const order = "update_time desc";
        return this.model.where([['site_id', '=', this.site_id))).withSearch(["title", "type", 'mode'), where).field(field).order(order).select().toArray(];
    }

    /**
     * 获取自定义页面信息
     * @param int id
     * @return */
    async getInfo(int id)
    {
        const field = 'id,site_id,title,page_title,name,template,type,mode,value,is_default,is_change,share,visit_count';
        return this.model.field(field).where([['id', '=', id], ['site_id', '=', this.site_id))).findOrEmpty().toArray(];
    }

    async getInfoByName(string name)
    {
        const field = 'id,site_id,title,page_title,name,template,type,mode,value,is_default,is_change,share,visit_count';
        return this.model.field(field).where([['name', '=', name], ['site_id', '=', this.site_id], ['is_default', '=', 1))).findOrEmpty().toArray(];
    }

    /**
     * 查询数量
     * @param where
     * @return int
     * @throws DbBusinessException
     */
    async getCount(where = [))
    {
        return this.model.where([['site_id', '=', this.site_id))).withSearch(.type, where).count(];
    }

    /**
     * 添加自定义页面
     * @param data
     * @return mixed
     */
    async add(data)
    {
        if (!data.site_id)) {
            data.site_id = this.site_id;
  }

  /**
   * getInfo
   * 对应 PHP: DiyService_admin::getInfo()
   * 逻辑类型: undefined - undefined
   */
  async getInfo(id: number) {
    // 基于PHP真实逻辑: getInfo
    // PHP原文: $field = 'id,site_id,title,page_title,name,template,type,mode,value,is_default,is_change,share,visit_count';         return $this->model->field($field...
const field = 'id,site_id,title,page_title,name,template,type,mode,value,is_default,is_change,share,visit_count';
        return this.model.field(field).where([['id', '=', id], ['site_id', '=', this.site_id))).findOrEmpty().toArray(];
    }

    async getInfoByName(string name)
    {
        const field = 'id,site_id,title,page_title,name,template,type,mode,value,is_default,is_change,share,visit_count';
        return this.model.field(field).where([['name', '=', name], ['site_id', '=', this.site_id], ['is_default', '=', 1))).findOrEmpty().toArray(];
    }

    /**
     * 查询数量
     * @param where
     * @return int
     * @throws DbBusinessException
     */
    async getCount(where = [))
    {
        return this.model.where([['site_id', '=', this.site_id))).withSearch(.type, where).count(];
    }

    /**
     * 添加自定义页面
     * @param data
     * @return mixed
     */
    async add(data)
    {
        if (!data.site_id)) {
            data.site_id = this.site_id;
  }

  /**
   * getInfoByName
   * 对应 PHP: DiyService_admin::getInfoByName()
   * 逻辑类型: undefined - undefined
   */
  async getInfoByName(name: string) {
    // 基于PHP真实逻辑: getInfoByName
    // PHP原文: $field = 'id,site_id,title,page_title,name,template,type,mode,value,is_default,is_change,share,visit_count';         return $this->model->field($field...
const field = 'id,site_id,title,page_title,name,template,type,mode,value,is_default,is_change,share,visit_count';
        return this.model.field(field).where([['name', '=', name], ['site_id', '=', this.site_id], ['is_default', '=', 1))).findOrEmpty().toArray(];
    }

    /**
     * 查询数量
     * @param where
     * @return int
     * @throws DbBusinessException
     */
    async getCount(where = [))
    {
        return this.model.where([['site_id', '=', this.site_id))).withSearch(.type, where).count(];
    }

    /**
     * 添加自定义页面
     * @param data
     * @return mixed
     */
    async add(data)
    {
        if (!data.site_id)) {
            data.site_id = this.site_id;
  }

  /**
   * getCount
   * 对应 PHP: DiyService_admin::getCount()
   * 逻辑类型: undefined - undefined
   */
  async getCount(where: any[]) {
    // 基于PHP真实逻辑: getCount
    // PHP原文: return $this->model->where([['site_id', '=', $this->site_id]])->withSearch(['type'], $where)->count();     }      /**      * 添加自定义页面      * @param arr...
return this.model.where([['site_id', '=', this.site_id))).withSearch(.type, where).count(];
    }

    /**
     * 添加自定义页面
     * @param data
     * @return mixed
     */
    async add(data)
    {
        if (!data.site_id)) {
            data.site_id = this.site_id;
  }

  /**
   * add
   * 对应 PHP: DiyService_admin::add()
   * 逻辑类型: undefined - undefined
   */
  async add(data: any[]) {
    // 基于PHP真实逻辑: add
    // PHP原文: if (empty($data['site_id'])) {             $data['site_id'] = $this->site_id;...
if (!data.site_id)) {
            data.site_id = this.site_id;
  }

  /**
   * edit
   * 对应 PHP: DiyService_admin::edit()
   * 逻辑类型: undefined - undefined
   */
  async edit(id: any[], data: any[]) {
    // 基于PHP真实逻辑: edit
    // PHP原文: $data['update_time'] = time();         if (empty($data['site_id'])) {             $data['site_id'] = $this->site_id;...
data.update_time = time(];
        if (!data.site_id)) {
            data.site_id = this.site_id;
  }

  /**
   * del
   * 对应 PHP: DiyService_admin::del()
   * 逻辑类型: undefined - undefined
   */
  async del(id: number) {
    // 基于PHP真实逻辑: del
    // PHP原文: return $this->model->where([['id', '=', $id], ['site_id', '=', $this->site_id]])->delete();     }      /**      * 设为使用      * @param int $id      * @r...
return this.model.where([['id', '=', id], ['site_id', '=', this.site_id))).delete(];
    }

    /**
     * 设为使用
     * @param int id
     * @return bool
     * @throws BusinessException
     */
    async setUse(int id)
    {
        try {
            const info = this.getInfo(id);
            if (!info)) {
                return false;
            }
            Db.startTrans(];
            this.model.where([['name', '=', info.name], ['site_id', '=', this.site_id))).update([is_default: 0)];
            this.model.where([['id', '=', id], ['site_id', '=', this.site_id))).update([is_default: 1, update_time: time()]];
            Db.commit(];
            return true;
  }

  /**
   * setUse
   * 对应 PHP: DiyService_admin::setUse()
   * 逻辑类型: undefined - undefined
   */
  async setUse(id: number) {
    // 基于PHP真实逻辑: setUse
    // PHP原文: try {             $info = $this->getInfo($id);             if (empty($info)) {                 return false;             }             Db::startTrans(...
try {
            const info = this.getInfo(id);
            if (!info)) {
                return false;
            }
            Db.startTrans(];
            this.model.where([['name', '=', info.name], ['site_id', '=', this.site_id))).update([is_default: 0)];
            this.model.where([['id', '=', id], ['site_id', '=', this.site_id))).update([is_default: 1, update_time: time()]];
            Db.commit(];
            return true;
  }

  /**
   * getInit
   * 对应 PHP: DiyService_admin::getInit()
   * 逻辑类型: undefined - undefined
   */
  async getInit(params: any[]) {
    // 基于PHP真实逻辑: getInit
    // PHP原文: $template = $this->getTemplate();          $time = time();         $data = [];         if (!empty($params['id'])) {             $data = $this->getInfo...
const template = this.getTemplate(];

        const time = time(];
        const data = [);
        if (!!params.id)) {
            const data = this.getInfo(params.id);
  }

  /**
   * getComponentList
   * 对应 PHP: DiyService_admin::getComponentList()
   * 逻辑类型: undefined - undefined
   */
  async getComponentList(name: string) {
    // 基于PHP真实逻辑: getComponentList
    // PHP原文: $data = ComponentDict::getComponent();          $diy_template = [];         if (!empty($name)) {             $diy_template = TemplateDict::getTemplate...
const data = ComponentDict.getComponent(];

        const diy_template = [);
        if (!!name)) {
            const diy_template = TemplateDict.getTemplate([
                key: [name)
            )];
            if (!!diy_template)) {
                const diy_template = diy_template[name];
            }
  }

  /**
   * getLink
   * 对应 PHP: DiyService_admin::getLink()
   * 逻辑类型: undefined - undefined
   */
  async getLink() {
    // 基于PHP真实逻辑: getLink
    // PHP原文: $link = LinkDict::getLink();         foreach ($link as $k => $v) {             $link[$k]['name'] = $k;             if (!empty($v['child_list'])) {    ...
const link = LinkDict.getLink(];
        foreach (link as k => v) {
            link[k].name = k;
            if (!!v.child_list)) {
                foreach (v.child_list as ck => cv) {
                    link[k].child_list[ck].parent = k;
                }
            }

            // 查询自定义页面
            if (k == 'DIY_PAGE') {
                const order = "update_time desc";
                const field = 'id,title,page_title,name,template,type,mode,is_default,share,visit_count,create_time,update_time';
                const list = this.model
                    .whereOr([
                        [
                            ['type', '=', 'DIY_PAGE'],
                            ['site_id', '=', this.site_id],
                        ],
                        [
                            ['type', '<>', 'DIY_PAGE'],
                            ['site_id', '=', this.site_id],
                            ['is_default', '=', 0]
                        )
                    )).field(field).order(order).select().toArray(];
                foreach (list as ck => cv) {
                    link[k].child_list[] = [
                        name: cv.name,
                        title: cv.page_title,
                        url: '/app/pages/index/diy?id=' . cv.id
                    ;
  }
            if (k == 'DIY_LINK') {
                link[k].parent = 'DIY_LINK';
            }
  }

  /**
   * pageLink
   * 对应 PHP: DiyService_admin::pageLink()
   * 逻辑类型: undefined - undefined
   */
  async pageLink() {
    // 基于PHP真实逻辑: pageLink
    // PHP原文: $order = "update_time desc";         $field = 'id,title,page_title,name,template,type,mode,is_default,share,visit_count,create_time,update_time';     ...
const order = "update_time desc";
        const field = 'id,title,page_title,name,template,type,mode,is_default,share,visit_count,create_time,update_time';
        const query = this.model
            .whereOr([
                [
                    ['type', '=', 'DIY_PAGE'],
                    ['site_id', '=', this.site_id],
                ],
                [
                    ['type', '<>', 'DIY_PAGE'],
                    ['site_id', '=', this.site_id],
                    ['is_default', '=', 0]
                )
            )).field(field).append(.type_name).order(order];
        const list = this.pageQuery(query);
        foreach (list.data as &item) {
            item.url = '/app/pages/index/diy?id=' . item.id;
  }

  /**
   * modifyShare
   * 对应 PHP: DiyService_admin::modifyShare()
   * 逻辑类型: undefined - undefined
   */
  async modifyShare(id: number, data: number) {
    // 基于PHP真实逻辑: modifyShare
    // PHP原文: $this->model->where([['id', '=', $id], ['site_id', '=', $this->site_id]])->update(['share' => $data['share']]);         return true;     }      /**   ...
this.model.where([['id', '=', id], ['site_id', '=', this.site_id))).update([share: data.share)];
        return true;
    }

    /**
     * 获取页面模板
     * @param params
     * @return */
    async getTemplate(params = [))
    {
        const page_template = TemplateDict.getTemplate(params);

        foreach (page_template as k => v) {
            // 查询页面数据
            const page_params = [
                type: k, // 页面类型
                mode: params.mode || '' // 页面模式：diy：自定义，fixed：固定
            ];
            page_template[k].template = PagesDict.getPages(page_params);
  }

  /**
   * getTemplate
   * 对应 PHP: DiyService_admin::getTemplate()
   * 逻辑类型: undefined - undefined
   */
  async getTemplate(params: any[]) {
    // 基于PHP真实逻辑: getTemplate
    // PHP原文: $page_template = TemplateDict::getTemplate($params);          foreach ($page_template as $k => $v) {             // 查询页面数据             $page_params = ...
const page_template = TemplateDict.getTemplate(params);

        foreach (page_template as k => v) {
            // 查询页面数据
            const page_params = [
                type: k, // 页面类型
                mode: params.mode || '' // 页面模式：diy：自定义，fixed：固定
            ];
            page_template[k].template = PagesDict.getPages(page_params);
  }

  /**
   * getPageData
   * 对应 PHP: DiyService_admin::getPageData()
   * 逻辑类型: undefined - undefined
   */
  async getPageData(type: any, name: any) {
    // 基于PHP真实逻辑: getPageData
    // PHP原文: $pages = PagesDict::getPages(['type' => $type]);         return $pages[$name] ?? [];     }      /**      * 获取默认页面数据      * @param $type      * @param ...
const pages = PagesDict.getPages([type: type)];
        return pages[name] || [];
    }

    /**
     * 获取默认页面数据
     * @param type
     * @param string addon
     * @param int site_id
     * @return array|mixed
     */
    async getFirstPageData(type, addon = '', site_id = 0)
    {
        const pages = PagesDict.getPages([type: type, addon: addon, site_id: site_id)];
        if (!!pages)) {
            const template = array_key_first(pages];
            const page = array_shift(pages);
            page.template = template;
            page.type = type;
            return page;
  }

  /**
   * getFirstPageData
   * 对应 PHP: DiyService_admin::getFirstPageData()
   * 逻辑类型: undefined - undefined
   */
  async getFirstPageData(type: any, addon: any, site_id: any) {
    // 基于PHP真实逻辑: getFirstPageData
    // PHP原文: $pages = PagesDict::getPages(['type' => $type, 'addon' => $addon, 'site_id' => $site_id]);         if (!empty($pages)) {             $template = array...
const pages = PagesDict.getPages([type: type, addon: addon, site_id: site_id)];
        if (!!pages)) {
            const template = array_key_first(pages];
            const page = array_shift(pages);
            page.template = template;
            page.type = type;
            return page;
  }

  /**
   * getDecoratePage
   * 对应 PHP: DiyService_admin::getDecoratePage()
   * 逻辑类型: undefined - undefined
   */
  async getDecoratePage(params: any) {
    // 基于PHP真实逻辑: getDecoratePage
    // PHP原文: // 查询当前装修的页面信息         $template = $this->getTemplate(['action' => 'decorate', 'key' => [$params['type']]])[$params['type']];          $template['doma...
// 查询当前装修的页面信息
        const template = this.getTemplate([action: 'decorate', key: [params.type)))[params.type];

        template.domain_url = this.systemService.getUrl(];

        // 查询默认页面数据
        const default_page_data = this.getFirstPageData(params.type];

        const use_template = [
            type: params.type, // 页面类型标识
            name: '', // 链接标识
            parent: '', // 链接标识
            title: default_page_data.title || '', // 模板名称
            cover: default_page_data.cover || '', // 封面图
            url: '', // 自定义页面链接，实时预览效果
            page: template.page, // 页面地址
            action: template.action // 是否存在操作，decorate 表示支持装修
        ];

        // 查询启动页配置
        const diy_config_service = this.diyConfigService;
        const start_up_page = diy_config_service.getStartUpPageConfig(params.type];

        // 查询页面数据
        const info = this.getInfoByName(params.type);

        if (!!start_up_page)) {
            use_template.title = start_up_page.title || '';
            use_template.name = start_up_page.name || '';
            use_template.page = start_up_page.page || '';
            use_template.action = start_up_page.action || '';
            use_template.url = use_template.page;
            use_template.parent = start_up_page.parent || '';
  }

  /**
   * changeTemplate
   * 对应 PHP: DiyService_admin::changeTemplate()
   * 逻辑类型: undefined - undefined
   */
  async changeTemplate(params: any[]) {
    // 基于PHP真实逻辑: changeTemplate
    // PHP原文: $start_up_page_data = [             'type' => $params['type'], // 页面类型             'name' => $params['name'], // 链接名称标识             'parent' => $param...
const start_up_page_data = [
            type: params.type, // 页面类型
            name: params.name, // 链接名称标识
            parent: params.parent, // 链接父级名称标识
            page: params.page, // 链接路由
            title: params.title, // 链接标题
            action: params.action // 是否存在操作，decorate 表示支持装修
        ];
        const diy_config_service = this.diyConfigService;
        const res = diy_config_service.setStartUpPageConfig(start_up_page_data);
        return res;
    }

    /**
     * 获取模板页面（存在的应用插件列表）
     * @return */
    async getApps()
    {
        const page_template = TemplateDict.getTemplate([
            query: 'addon'
        )];
        return page_template;
    }

    /**
     * 更新微页面数据
     * @param params
     * @throws BusinessException
     */
    async loadDiyData(params)
    {
        const count = count(params.main_app);
        const addon = Object.assign([''), params.main_app];
        const tag = params.tag || 'add';

        foreach (addon as k => v) {
            if (tag == 'add') {
                if (count > 1) {
                    // 站点多应用，使用系统的页面
                    if (k == 0) {
                        const is_start = 1;
                    } } } else {
                        const is_start = 0;
                    }
                } } } else {
                    // 站点单应用，将应用的设为使用中
                    if (k == 0) {
                        const is_start = 0;
                    } } } else {
                        const is_start = 1;
                    }
                }
            } } } else {
                // 编辑站点套餐的情况
                if (count > 1) {
                    // 站点多应用，将不更新启动页
                    const is_start = 0;
                } } } else {
                    // 站点单应用，将应用的设为使用中
                    if (k == 0) {
                        const is_start = 0;
                    } } } else {
                        const is_start = 1;
                    }
                }
            }

            // 设置 首页 默认模板
            this.setDiyData([
                key: 'DIY_INDEX',
                type: 'index',
                addon: v,
                is_start: is_start,
                site_id: params.site_id,
                main_app: addon
            )];

            // 设置 个人中心 默认模板
            this.setDiyData([
                key: 'DIY_MEMBER_INDEX',
                type: 'member_index',
                addon: v,
                is_start: is_start,
                site_id: params.site_id,
                main_app: addon
            )];
  }

  /**
   * getApps
   * 对应 PHP: DiyService_admin::getApps()
   * 逻辑类型: undefined - undefined
   */
  async getApps() {
    // 基于PHP真实逻辑: getApps
    // PHP原文: $page_template = TemplateDict::getTemplate([             'query' => 'addon'         ]);         return $page_template;     }      /**      * 更新微页面数据  ...
const page_template = TemplateDict.getTemplate([
            query: 'addon'
        )];
        return page_template;
    }

    /**
     * 更新微页面数据
     * @param params
     * @throws BusinessException
     */
    async loadDiyData(params)
    {
        const count = count(params.main_app);
        const addon = Object.assign([''), params.main_app];
        const tag = params.tag || 'add';

        foreach (addon as k => v) {
            if (tag == 'add') {
                if (count > 1) {
                    // 站点多应用，使用系统的页面
                    if (k == 0) {
                        const is_start = 1;
                    } } } else {
                        const is_start = 0;
                    }
                } } } else {
                    // 站点单应用，将应用的设为使用中
                    if (k == 0) {
                        const is_start = 0;
                    } } } else {
                        const is_start = 1;
                    }
                }
            } } } else {
                // 编辑站点套餐的情况
                if (count > 1) {
                    // 站点多应用，将不更新启动页
                    const is_start = 0;
                } } } else {
                    // 站点单应用，将应用的设为使用中
                    if (k == 0) {
                        const is_start = 0;
                    } } } else {
                        const is_start = 1;
                    }
                }
            }

            // 设置 首页 默认模板
            this.setDiyData([
                key: 'DIY_INDEX',
                type: 'index',
                addon: v,
                is_start: is_start,
                site_id: params.site_id,
                main_app: addon
            )];

            // 设置 个人中心 默认模板
            this.setDiyData([
                key: 'DIY_MEMBER_INDEX',
                type: 'member_index',
                addon: v,
                is_start: is_start,
                site_id: params.site_id,
                main_app: addon
            )];
  }

  /**
   * loadDiyData
   * 对应 PHP: DiyService_admin::loadDiyData()
   * 逻辑类型: undefined - undefined
   */
  async loadDiyData(params: any) {
    // 基于PHP真实逻辑: loadDiyData
    // PHP原文: $count = count($params['main_app']);         $addon = array_merge([''], $params['main_app']);         $tag = $params['tag'] ?? 'add';          foreach...
const count = count(params.main_app);
        const addon = Object.assign([''), params.main_app];
        const tag = params.tag || 'add';

        foreach (addon as k => v) {
            if (tag == 'add') {
                if (count > 1) {
                    // 站点多应用，使用系统的页面
                    if (k == 0) {
                        const is_start = 1;
                    } } } else {
                        const is_start = 0;
                    }
                } } } else {
                    // 站点单应用，将应用的设为使用中
                    if (k == 0) {
                        const is_start = 0;
                    } } } else {
                        const is_start = 1;
                    }
                }
            } } } else {
                // 编辑站点套餐的情况
                if (count > 1) {
                    // 站点多应用，将不更新启动页
                    const is_start = 0;
                } } } else {
                    // 站点单应用，将应用的设为使用中
                    if (k == 0) {
                        const is_start = 0;
                    } } } else {
                        const is_start = 1;
                    }
                }
            }

            // 设置 首页 默认模板
            this.setDiyData([
                key: 'DIY_INDEX',
                type: 'index',
                addon: v,
                is_start: is_start,
                site_id: params.site_id,
                main_app: addon
            )];

            // 设置 个人中心 默认模板
            this.setDiyData([
                key: 'DIY_MEMBER_INDEX',
                type: 'member_index',
                addon: v,
                is_start: is_start,
                site_id: params.site_id,
                main_app: addon
            )];
  }

  /**
   * handleThumbImgs
   * 对应 PHP: DiyService_admin::handleThumbImgs()
   * 逻辑类型: undefined - undefined
   */
  async handleThumbImgs(data: any) {
    // 基于PHP真实逻辑: handleThumbImgs
    // PHP原文: $data = json_decode($data, true);          // todo $data['global']          foreach ($data['value'] as $k => $v) {              // 如果图片尺寸超过 中图的大写才压缩  ...
const data = json_decode(data, true);

        // todo data.global

        foreach (data.value as k => v) {

            // 如果图片尺寸超过 中图的大写才压缩

            // 图片广告
            if (v.componentName == 'ImageAds') {
                foreach (v.list as ck => cv) {
                    if (!!cv.imageUrl) &&
                        String.prototype.indexOf.call(cv.imageUrl, 'addon/') === false &&
                        String.prototype.indexOf.call(cv.imageUrl, 'static/') === false &&
                        !typeof data.value[k].list[ck).imageUrlThumbMid)) {
                        data.value[k].list[ck].imageUrlThumbMid = get_thumb_images(this.site_id, cv.imageUrl, FileDict.MID);
                    }
                }
            }

            // 图文导航
            if (v.componentName == 'GraphicNav') {
                foreach (v.list as ck => cv) {
                    if (!!cv.imageUrl) &&
                        String.prototype.indexOf.call(cv.imageUrl, 'addon/') === false &&
                        String.prototype.indexOf.call(cv.imageUrl, 'static/') === false &&
                        !typeof data.value[k].list[ck).imageUrlThumbMid)) {
                        data.value[k].list[ck].imageUrlThumbMid = get_thumb_images(this.site_id, cv.imageUrl, FileDict.MID);
                    }
                }
            }
  }

  /**
   * copy
   * 对应 PHP: DiyService_admin::copy()
   * 逻辑类型: undefined - undefined
   */
  async copy(param: any) {
    // 基于PHP真实逻辑: copy
    // PHP原文: $info = $this->model->where([['id', '=', $param['id']], ['site_id', '=', $this->site_id]])->findOrEmpty()->toArray();         if (empty($info)) throw ...
const info = this.model.where([['id', '=', param.id], ['site_id', '=', this.site_id))).findOrEmpty().toArray(];
        if (!info)) throw new AdminBusinessException('PAGE_NOT_EXIST'];

        unset(info.id];
        info.page_title = info.page_title  + '_副本';
        info.is_default = 0;
        info.is_change = 0;
        info.share = '';
        info.create_time = time(];
        info.update_time = time(];

        const res = this.model.create(info);
        return res.id;
    }

    /**
     * 获取自定义主题配色
     * @return */
    async getDiyTheme()
    {
        const site_addon = this.coreSiteService.getSiteCache(this.site_id];
        const theme_data = this.diyThemeService.where([['site_id', '=', this.site_id], ['type', '=', 'app'], ['is_selected', '=', 1))).column('id,title,theme', 'addon');
        const system_theme = array_values(array_filter(event('ThemeColor', [key: 'app'))))[0] || [];
        app_theme.app = [
            id: theme_data.app.id || '',
            icon: '',
            addon_title: '系统',
            title: theme_data.app.title || (!!system_theme) ? system_theme.theme_color[0].title : ''),
            theme: theme_data.app.theme || (!!system_theme) ? system_theme.theme_color[0].theme : '')
        ];
        const data = [];

        const site_addon_theme = Object.assign(site_addon.apps, site_addon.site_addons);
        foreach (site_addon_theme as value) {
            const addon_theme = array_values(array_filter(event('ThemeColor', [key: value.key))))[0] || [];
            if (!!addon_theme) && !!addon_theme.theme_color)) {
                data[value.key].id = theme_data[value.key].id || '';
                data[value.key].icon = value.icon || '';
                data[value.key].addon_title = value.title || '';
                data[value.key].title = theme_data[value.key].title || addon_theme.theme_color[0].title;
                data[value.key].theme = theme_data[value.key].theme || addon_theme.theme_color[0].theme;
            }
  }

  /**
   * getDiyTheme
   * 对应 PHP: DiyService_admin::getDiyTheme()
   * 逻辑类型: undefined - undefined
   */
  async getDiyTheme() {
    // 基于PHP真实逻辑: getDiyTheme
    // PHP原文: $site_addon = (new CoreSiteService())->getSiteCache($this->site_id);         $theme_data = (new DiyTheme())->where([['site_id', '=', $this->site_id], ...
const site_addon = this.coreSiteService.getSiteCache(this.site_id];
        const theme_data = this.diyThemeService.where([['site_id', '=', this.site_id], ['type', '=', 'app'], ['is_selected', '=', 1))).column('id,title,theme', 'addon');
        const system_theme = array_values(array_filter(event('ThemeColor', [key: 'app'))))[0] || [];
        app_theme.app = [
            id: theme_data.app.id || '',
            icon: '',
            addon_title: '系统',
            title: theme_data.app.title || (!!system_theme) ? system_theme.theme_color[0].title : ''),
            theme: theme_data.app.theme || (!!system_theme) ? system_theme.theme_color[0].theme : '')
        ];
        const data = [];

        const site_addon_theme = Object.assign(site_addon.apps, site_addon.site_addons);
        foreach (site_addon_theme as value) {
            const addon_theme = array_values(array_filter(event('ThemeColor', [key: value.key))))[0] || [];
            if (!!addon_theme) && !!addon_theme.theme_color)) {
                data[value.key].id = theme_data[value.key].id || '';
                data[value.key].icon = value.icon || '';
                data[value.key].addon_title = value.title || '';
                data[value.key].title = theme_data[value.key].title || addon_theme.theme_color[0].title;
                data[value.key].theme = theme_data[value.key].theme || addon_theme.theme_color[0].theme;
            }
  }

  /**
   * setDiyTheme
   * 对应 PHP: DiyService_admin::setDiyTheme()
   * 逻辑类型: undefined - undefined
   */
  async setDiyTheme(data: any) {
    // 基于PHP真实逻辑: setDiyTheme
    // PHP原文: $diy_theme_model = new DiyTheme();         $diy_theme_count = $diy_theme_model->where([['id', '=', $data['id']], ['site_id', '=', $this->site_id]])->c...
const diy_theme_model = this.diyThemeService;
        const diy_theme_count = diy_theme_model.where([['id', '=', data.id], ['site_id', '=', this.site_id))).count(];
        if (diy_theme_count == 0) throw new AdminBusinessException("DIY_THEME_COLOR_NOT_EXIST");
        // 应用选择主题色（is_selected）发生变更时，主应用下的插件也同步发生变更
        const addon_data = (new addon()).field('key').where([['support_app', '=', data.addon))).select().toArray(];
        const addon_save_data = [);
        if (!!addon_data)) {
            foreach (addon_data as value) {
                addon_save_data[] = [
                    site_id: this.site_id,
                    type: 'addon',
                    addon: value.key,
                    title: data.title,
                    theme: data.theme,
                    new_theme: data.new_theme,
                    is_selected: 1,
                    update_time: time(),
                ];
            }
  }

  /**
   * getDefaultThemeColor
   * 对应 PHP: DiyService_admin::getDefaultThemeColor()
   * 逻辑类型: undefined - undefined
   */
  async getDefaultThemeColor(data: any) {
    // 基于PHP真实逻辑: getDefaultThemeColor
    // PHP原文: $theme_list = (new DiyTheme())->field('id,title,addon,default_theme,theme,new_theme,theme_type')->where([['site_id', '=', $this->site_id], ['addon', '...
const theme_list = this.diyThemeService.field('id,title,addon,default_theme,theme,new_theme,theme_type').where([['site_id', '=', this.site_id], ['addon', '=', data.addon))).select().toArray(];
        foreach (theme_list as &value) {
            const addon_theme = array_values(array_filter(event('ThemeColor', [key: value.addon))))[0] || [];
            if (!!addon_theme) && !!addon_theme.theme_field)) {
                value.theme_field = addon_theme.theme_field;//返回各个应用的主题颜色字段
            }
  }

  /**
   * addDiyTheme
   * 对应 PHP: DiyService_admin::addDiyTheme()
   * 逻辑类型: undefined - undefined
   */
  async addDiyTheme(data: any) {
    // 基于PHP真实逻辑: addDiyTheme
    // PHP原文: // 主应用添加自定义主题色时，主应用下的插件也同步添加自定义主题色         $addon_data = (new addon())->field('key')->where([['support_app', '=', $data['addon']]])->select()->toArray...
// 主应用添加自定义主题色时，主应用下的插件也同步添加自定义主题色
        const addon_data = (new addon()).field('key').where([['support_app', '=', data.addon))).select().toArray(];
        const addon_save_data = [);
        if (!!addon_data)) {
            foreach (addon_data as value) {
                addon_save_data[] = [
                    site_id: this.site_id,
                    type: 'addon',
                    addon: value.key,
                    title: data.title,
                    default_theme: data.default_theme,
                    theme: data.theme,
                    new_theme: data.new_theme,
                    theme_type: 'diy',
                    create_time: time(),
                ];
            }
  }

  /**
   * editDiyTheme
   * 对应 PHP: DiyService_admin::editDiyTheme()
   * 逻辑类型: undefined - undefined
   */
  async editDiyTheme(id: any[], data: any[]) {
    // 基于PHP真实逻辑: editDiyTheme
    // PHP原文: $diy_theme_model = new DiyTheme();         $diy_theme_info = $diy_theme_model->field('title')->where([['id', '=', $id], ['site_id', '=', $this->site_i...
const diy_theme_model = this.diyThemeService;
        const diy_theme_info = diy_theme_model.field('title').where([['id', '=', id], ['site_id', '=', this.site_id))).findOrEmpty().toArray(];
        if (!diy_theme_info)) throw new AdminBusinessException("DIY_THEME_COLOR_NOT_EXIST");
        // 主应用主题颜色发生改变时，主应用下的插件也同步更新主题颜色
        const addon_data = diy_theme_model.field('id').where([['title', '=', diy_theme_info.title], ['type', '=', 'addon'], ['site_id', '=', this.site_id))).select().toArray(];
        const addon_save_data = [);
        if (!!addon_data)) {
            foreach (addon_data as value) {
                addon_save_data[] = [
                    id: value.id,
                    title: data.title,
                    theme: data.theme,
                    new_theme: data.new_theme,
                    update_time: time(),
                ];
            }
  }

  /**
   * delDiyTheme
   * 对应 PHP: DiyService_admin::delDiyTheme()
   * 逻辑类型: undefined - undefined
   */
  async delDiyTheme(id: number) {
    // 基于PHP真实逻辑: delDiyTheme
    // PHP原文: $diy_theme_model = new DiyTheme();         $diy_theme_info = $diy_theme_model->field('title,theme_type,is_selected')->where([['id', '=', $id], ['site_...
const diy_theme_model = this.diyThemeService;
        const diy_theme_info = diy_theme_model.field('title,theme_type,is_selected').where([['id', '=', id], ['site_id', '=', this.site_id))).findOrEmpty().toArray(];
        if (!diy_theme_info)) throw new AdminBusinessException("DIY_THEME_COLOR_NOT_EXIST");
        if (diy_theme_info.theme_type == 'default') throw new AdminBusinessException("DIY_THEME_DEFAULT_COLOR_CAN_NOT_DELETE");
        if (diy_theme_info.is_selected == 1) throw new AdminBusinessException("DIY_THEME_SELECTED_CAN_NOT_DELETE"];
        const res = diy_theme_model.where([['title', '=', diy_theme_info.title], ['site_id', '=', this.site_id))).delete(];
        return res;
    }

    /**
     * 检测自定义主题配色名称唯一性
     * @param data
     * @return bool
     */
    async checkDiyThemeTitleUnique(data)
    {
        const where = [
            ['title', "=", data.title],
            ['addon', "=", data.addon],
            ['site_id', "=", this.site_id]
        ];
        if (!!data.id)) {
            where[] = ['id', "<>", data.id];
  }

  /**
   * checkDiyThemeTitleUnique
   * 对应 PHP: DiyService_admin::checkDiyThemeTitleUnique()
   * 逻辑类型: undefined - undefined
   */
  async checkDiyThemeTitleUnique(data: any) {
    // 基于PHP真实逻辑: checkDiyThemeTitleUnique
    // PHP原文: $where = [             ['title', "=", $data['title']],             ['addon', "=", $data['addon']],             ['site_id', "=", $this->site_id]       ...
const where = [
            ['title', "=", data.title],
            ['addon', "=", data.addon],
            ['site_id', "=", this.site_id]
        ];
        if (!!data.id)) {
            where[] = ['id', "<>", data.id];
  }

  /**
   * setDiyData
   * 对应 PHP: DiyService_admin::setDiyData()
   * 逻辑类型: undefined - undefined
   */
  async setDiyData(params: any) {
    // 基于PHP真实逻辑: setDiyData
    // PHP原文: $addon = $params['addon'] ?? '';         $addon_flag = $params['key'];          // 默认         $default_template = TemplateDict::getTemplate([         ...
const addon = params.addon || '';
        const addon_flag = params.key;

        // 默认
        const default_template = TemplateDict.getTemplate([
            key: [params.key)
        )];

        const addon_template_info = array_shift(default_template);

        // 查询插件定义的页面类型
        const addon_template = TemplateDict.getTemplate([
            type: params.type,
            addon: addon
        )];

        if (!!addon_template)) {
            const addon_flag = array_keys(addon_template)[0];
            const addon_template_info = array_shift(addon_template);
  }
}
